package org.lionsoul.websnail.util;

import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Url serial utils
 *
 * @author chenxin<chenxin619315 @ gmail.com>
 */
public class WebUtils {
    private static final Pattern charsetPattern = Pattern.compile("charset\\s*=\\s*['\"]*([^\\s;'\"]*)");

    /**
     * get the charset value from string contains a part like
     * 'charset=utf-8'
     */
    public static String getCharset(String str) {
        Matcher matcher = charsetPattern.matcher(str);
        if (matcher.find()) {
            String charset = matcher.group(1);       //get the $1 as the charset value
            if (Charset.isSupported(charset)) {    //check the support of the charset
                return charset;
            }
        }

        return null;
    }

    public static Host getHost(String url) {
        int startPos = url.indexOf("://");
        if (startPos == -1) {
            return new Host(null, null);
        }
        String scheme = url.substring(0, startPos);
        int endPos = url.indexOf("/", startPos + 4);
        if (endPos == -1) {
            return new Host(scheme, url.substring(startPos + 3).toLowerCase());
        } else {
            return new Host(scheme, url.substring(startPos + 3, endPos).toLowerCase());
        }
    }


}
